﻿using UnityEngine;
using UnityEngine.EventSystems;
[RequireComponent(typeof(UnityEngine.UI.AspectRatioFitter))]
public class MobileInputController : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler,IPointerDownHandler,IPointerUpHandler {

    public RectTransform Background;
    public RectTransform Knob;
    public Canvas canvas;

    public Transform player;//需要操控的目标


    public float offset;
    Vector2 PointPosition;

    public void OnBeginDrag(PointerEventData eventData)
    {
        
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 eventdata = eventData.position;
        if (canvas.renderMode==RenderMode.ScreenSpaceCamera)
        {
            Vector3 worldPos = Camera.main.ScreenToWorldPoint(eventData.position);//Camera.main指的是UI摄像机
            eventdata = canvas.transform.InverseTransformPoint(worldPos);
        }
        if (canvas.renderMode == RenderMode.ScreenSpaceCamera)
        {
            PointPosition = new Vector2((eventdata.x - Background.localPosition.x) / ((Background.rect.size.x - Knob.rect.size.x) / 2), (eventdata.y - Background.localPosition.y) / ((Background.rect.size.y - Knob.rect.size.y) / 2));
        }
        else
        {
            PointPosition = new Vector2((eventdata.x - Background.position.x) / ((Background.rect.size.x - Knob.rect.size.x) / 2), (eventdata.y - Background.position.y) / ((Background.rect.size.y - Knob.rect.size.y) / 2));
        }
     
        PointPosition = (PointPosition.magnitude>1.0f)?PointPosition.normalized :PointPosition;
        if (canvas.renderMode == RenderMode.ScreenSpaceCamera)
        {
            Knob.transform.localPosition = new Vector2((PointPosition.x * ((Background.rect.size.x - Knob.rect.size.x) / 2) * offset), (PointPosition.y * ((Background.rect.size.y - Knob.rect.size.y) / 2) * offset));
        }
        else
        {
            Knob.transform.position = new Vector2((PointPosition.x * ((Background.rect.size.x - Knob.rect.size.x) / 2) * offset) + Background.position.x, (PointPosition.y * ((Background.rect.size.y - Knob.rect.size.y) / 2) * offset) + Background.position.y);
        }
        player.transform.localPosition = player.transform.localPosition + new Vector3(PointPosition.x*10f, PointPosition.y * 10f,0f);


    }

    public void OnEndDrag(PointerEventData eventData)
    {
        PointPosition = new Vector2(0f,0f);
        Knob.transform.position = Background.position;
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        OnDrag(eventData);
       
    }

    public void OnPointerUp(PointerEventData eventData) {
        OnEndDrag(eventData);
    }
   
	
	// Update is called once per frame
	void Update () {

    }
}
